package com.xm.ojcodesandbox.controller;

import com.xm.ojcodesandbox.JavaNativeSandbox;
import com.xm.ojcodesandbox.model.ExecuteCodeRequest;
import com.xm.ojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {

    public static final String AUTH_REQUEST_HEADER = "Authorization";

    public static final String AUTH_REQUEST_REQUEST = "Secret";
    @Resource
    private JavaNativeSandbox javaNativeSandbox;
    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }

    /**
     * 对外开放API
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/execCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                           HttpServletResponse response) {
        String header = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_REQUEST.equals(header)){
            response.setStatus(403);
            return null;
        }
        ExecuteCodeResponse executeCodeResponse = javaNativeSandbox.executeCode(executeCodeRequest);
        if (executeCodeResponse == null) {
            throw new RuntimeException("请求参数为空");
        }
        return executeCodeResponse;
    }
}
